package com.ruslan.magaz.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ruslan.magaz.domain.Cart;
import com.ruslan.magaz.domain.Category;
import com.ruslan.magaz.domain.Customer;
import com.ruslan.magaz.domain.Product;
import com.ruslan.magaz.domain.Rating;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.ItemService;
import com.ruslan.magaz.service.OrderService;
import com.ruslan.magaz.service.UserService;

@Controller
@RequestMapping("/admin/product")
public class AdminProduct {
	public static int PRODUCTS_PAGE_SIZE = 20;
	public static int REVIEWS_PAGE_SIZE = 5;

	@Autowired
	private UserService userService;
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private OrderService orderService;
	
	@ModelAttribute("categories")
	 public List<Category> getAllCategories() {
	  return itemService.getAllCategories();
	}
	
	List<String> formCategoryNames(){
		List<Category> categories = itemService.getAllCategories();
 		List<String> categoryNames = new ArrayList<String>();
 		for (Category c:categories){
 			categoryNames.add(c.getName());
 		}
 		return categoryNames;
	}
	Integer getCategoryId(String name, List<Category> categories){
		for(Category c:categories){
			if (c.getName().equals(name)){
				return c.getCategoryId();
			}
		}
		return null;
	}
	
	@RequestMapping(value="")
    public String adminProducts(HttpServletRequest req, HttpServletResponse res, @RequestParam(required=false) Integer categoryId, @RequestParam(required = false) Integer pageNum, Model model) throws ServletException, IOException{
			if (pageNum == null){
				pageNum=1;
			}
			if (categoryId == null){
				categoryId=itemService.getFirstCategoryId();
			}
			int lastPageNum = itemService.productsForCategoryPageCount(categoryId, PRODUCTS_PAGE_SIZE);
	 		List<Product> products = itemService.getAllProductsForCategory(categoryId, pageNum, PRODUCTS_PAGE_SIZE);
	 		Product product = new Product();
	 		model.addAttribute("products", products);
	 		model.addAttribute("product", product);
	 		model.addAttribute("lastPageNum", lastPageNum);
	 		model.addAttribute("categoryId", categoryId);
	        return "adminTiles/adminProducts";
	 }
	
	@RequestMapping(value="", method=RequestMethod.POST)
    public String postProducts(HttpServletRequest req, HttpServletResponse res, @RequestParam(required=false) Integer categoryId, @RequestParam(required = false) Integer pageNum, Model model,@Valid @ModelAttribute("product") Product product, BindingResult bindingResult) throws ServletException, IOException{
		if (categoryId == null){
			categoryId=1;
		}
		if(bindingResult.hasErrors()){
			 return "redirect:/admin/product?categoryId="+categoryId;
		 }
		itemService.editProduct(product);
		String referer = req.getHeader("Referer");
        return "redirect:"+ referer;
	 }
	
	@RequestMapping(value="/edit")
    public String editProduct(HttpServletRequest req, HttpServletResponse res, @RequestParam Integer productId, Model model) throws ServletException, IOException{
	 		Product product = itemService.getProductById(productId);
			model.addAttribute("categoryNames", itemService.getCategoryNames());  
	 		model.addAttribute("product", product);
	 		model.addAttribute("add", false);
	        return "adminTiles/adminEditProduct";
	}
	
	@RequestMapping(value="/edit", method=RequestMethod.POST)
    public String editProductPost(HttpServletRequest req, HttpServletResponse res, Model model, @Valid @ModelAttribute Product product, BindingResult bindingResult) throws ServletException, IOException{
		if(bindingResult.hasErrors()){
			model.addAttribute("categoryNames", itemService.getCategoryNames());
			return "adminTiles/adminEditProduct";
		}
		Integer categoryId = itemService.getCategoryByName(product.getCategory().getName()).getCategoryId();
		if (categoryId == null){
			model.addAttribute("categoryNames", itemService.getCategoryNames());
			model.addAttribute("categoryNotExists",true);
			return "adminTiles/adminEditProduct";
		}
		product.setCategory(new Category(categoryId));
		itemService.deepEditProduct(product);
	    return "redirect:/admin/product?categoryId="+product.getCategory().getCategoryId();
	}
	
	
	@RequestMapping(value="/add", method= RequestMethod.GET)
    public String addProduct(HttpServletRequest req, HttpServletResponse res, @RequestParam Integer categoryId, Model model) throws ServletException, IOException{
			Product product = new Product();
//			Category category = itemService.getCategoryById(categoryId);
			product.setCategory(new Category(categoryId));
			model.addAttribute("product", product);
			model.addAttribute("add", true);
	        return "adminTiles/adminEditProduct";
	 }
	
	@RequestMapping(value="/add", method= RequestMethod.POST)
    public String addProductPost(HttpServletRequest req, HttpServletResponse res, Model model,@Valid @ModelAttribute("product") Product product, BindingResult bindingResult) throws ServletException, IOException{
		if(bindingResult.hasErrors()){
			 return "adminTiles/adminEditProduct";
		}
		Integer categoryId = itemService.getCategoryByName(product.getCategory().getName()).getCategoryId();
		if (categoryId == null){
			model.addAttribute("categoryNames", itemService.getCategoryNames());
			model.addAttribute("categoryNotExists",true);
			return "adminTiles/adminEditProduct";
		}
		product.setCategory(new Category(categoryId));
		itemService.addProduct(product);
		return "redirect:/admin/product?categoryId="+product.getCategory().getCategoryId();
	 }
}
